package listbyorder.access301_400.test350;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution1 {

    // 两个数组的交集
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int n1 = nums1.length;
        int n2 = nums2.length;
        if (n1 < n2) {
            return getAns(nums1, nums2);
        } else {
            return getAns(nums2, nums1);
        }
    }

    // 获取两个数的交集
    private int[] getAns(int[] nums1, int[] nums2) {
        List<Integer> list = new ArrayList<>();
        int c1 = 0;
        int c2 = 0;
        while (c1 < nums1.length && c2 < nums2.length) {
            if (nums1[c1] == nums2[c2]) {
                list.add(nums1[c1]);
                c1++;
                c2++;
            } else if (nums1[c1] < nums2[c2]) {
                c1++;
            } else {
                c2++;
            }
        }
        int[] res = new int[list.size()];
        int index = 0;
        for (Integer num : list) {
            res[index++] = num;
        }
        return res;
    }
}
